package com.lianjia.sh.se.esb.server.action;

import com.alibaba.fastjson.JSONObject;
import com.dooioo.dymq.listener.common.AbstractListener;
import com.lianjia.sh.se.esb.server.annotation.MessageActionCfg;
import com.lianjia.sh.se.esb.server.log.MessageLogInterceptor;
import com.lianjia.sh.se.esb.spi.model.Message;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import javax.jms.JMSException;
import java.util.Map;

/**
 * Created by yangsp1 on 16/7/18.
 */
public abstract class AbstractActiveMQMessageAction extends AbstractListener implements MessageAction {
    Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    MessageLogInterceptor messageLogInterceptor;

    @Override
    public void onMessage(String messageJson) throws JMSException {
        Message message = JSONObject.parseObject(messageJson,Message.class);
        if(message == null){
            return;
        }
        //是否匹配
        if(!isMatch(message)) {
            return;
        }

        //aop无法穿透内部方法调用,因此使用回调
        if(messageLogInterceptor != null){
            messageLogInterceptor.beforeExecuteMessage(this,message);
        }
        try {
            executeMessage(message);
            if(messageLogInterceptor != null) {
                messageLogInterceptor.afterExecuteMessageSuccess(this, message);
            }
        }catch (Exception e){
            logger.error(e.getMessage(),e);
            if(messageLogInterceptor != null) {
                messageLogInterceptor.afterExecuteMessageFail(this, message);
            }
            throw e;
        }
    }

    @Override
    public boolean isMatch(Message message) {
        MessageActionCfg messageActionCfg = this.getClass().getAnnotation(MessageActionCfg.class);
        Map<String,Object> extendData = message.getExtendData();//扩展数据，包含：actionType
        //如果没有配置，没有actionType配置，或者消息中actionType为空（只有失败重发时才有），且actionType不一致，则为不匹配
        if(messageActionCfg != null && extendData != null
                && message.getExtendData().get("actionType") != null
                && messageActionCfg.actionType() != null
                && !messageActionCfg.actionType().equals(message.getExtendData().get("actionType"))){
            return false;
        }
        return true;
    }
}
